import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getAppName } from '@/utils/config'
import { ElMessage } from 'element-plus'

// 获取应用名称
const APP_NAME = getAppName()

const routes = [
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/views/Layout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘' }
      },
      // 用户管理
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/Users.vue'),
        meta: { 
          title: '用户列表',
          permissions: ['user:list']
        }
      },
      {
        path: 'departments',
        name: 'Departments',
        component: () => import('@/views/Departments.vue'),
        meta: { 
          title: '部门管理',
          permissions: ['department:list']
        }
      },
      {
        path: 'roles',
        name: 'Roles',
        component: () => import('@/views/Roles.vue'),
        meta: { 
          title: '角色管理',
          permissions: ['role:list']
        }
      },
      // 权限管理
      {
        path: 'permissions',
        name: 'Permissions',
        component: () => import('@/views/Permissions.vue'),
        meta: {
          title: '权限管理',
          permissions: ['permission:list']
        }
      },
      // 智能体管理
      {
        path: 'agents',
        name: 'Agents',
        component: () => import('@/views/Agents.vue'),
        meta: {
          title: '智能体管理'
        }
      },
      // 操作日志
      {
        path: 'request-logs',
        name: 'RequestLogs',
        component: () => import('@/views/RequestLogs.vue'),
        meta: { 
          title: '请求日志',
          permissions: ['log:request']
        }
      },
      {
        path: 'login-history',
        name: 'LoginHistory',
        component: () => import('@/views/LoginHistory.vue'),
        meta: { 
          title: '登录历史',
          permissions: ['log:login']
        }
      },
      // 个人信息
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人信息' }
      }
    ]
  },
  {
    path: '/redirect',
    component: () => import('@/views/Layout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/Redirect.vue'),
        meta: { title: '页面重定向' }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { title: '页面未找到' }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫，处理身份验证和权限
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - ${APP_NAME}` : APP_NAME
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const userStore = useUserStore()
    if (!userStore.isLoggedIn) {
      // 未登录，重定向到登录页
      next({ name: 'Login', query: { redirect: to.fullPath } })
      return
    }
    
    // 如果访问的是根路径（Dashboard），重定向到个人信息页面
    if (to.path === '/' || to.name === 'Dashboard') {
      next({ name: 'Profile' })
      return
    }
    
    // 检查是否有权限访问
    if (to.meta.permissions && to.meta.permissions.length > 0) {
      if (!userStore.hasAnyPermission(to.meta.permissions)) {
        ElMessage.error('您没有权限访问此页面')
        if (from.name) {
          // 如果是从其他页面跳转过来的，返回上一页
          next(false)
        } else {
          // 否则跳转到个人信息页面
          next({ name: 'Profile' })
        }
        return
      }
    }
    
    next()
  } else {
    // 已登录用户访问无需登录的页面（如登录页），重定向到个人信息页面
    if (to.path === '/login') {
      const userStore = useUserStore()
      if (userStore.isLoggedIn) {
        next({ name: 'Profile' })
        return
      }
    }
    
    next()
  }
})

export default router 